/*
 * @Author: evan.wan
 * @Date:   2016-06-25 15:55:20
 */

'use strict';
define([
    'underscore',
    '../../../common/service',
    'text!../tpl/brandLogo.html'
], function(
    _,
    http,
    tpl
) {
    function me() {
        var self = this;
        self.defaultColor = "white";
        this.init = function(templateId, callback) {
            self.templateId = templateId;
            self.callback = callback;
            self.$root = $('#tab-content1');
            self.render();
        }

        this.render = function() {
            self.$root.html(I18N.parse(tpl, 'templateDetail'));
            self.event();
            self.initAddLogoDialog();
            //一进页面就请求一次列表
            self.initList();
        }

        this.initAddLogoDialog = function(){
            var _modal = self.$root.find("#add-logo-dialog");
            _modal.modal({
                backdrop: 'static',
                keyboard: false,
                show:false
            });

            _modal.off('show.bs.modal').on('show.bs.modal', function (e) {
                _modal.find(".error-remainder").addClass("hide");
                _modal.find('div.ndp-drop-wrapper[name="product-drop"]').drop("val", {val : -1 , text : I18N.getText('templateDetail' , 'pleaseSelectWebsite')});
                _modal.find(".choose-info").removeClass("hide");
                _modal.find('.upload-info').addClass("hide");
                _modal.find(".upload-result-c").empty();
                //清空已选的文件
                _modal.find('input[name="file"]', ".add-logo-container").val("");
                self.needRefreshList = false;
            });

            _modal.off('hide.bs.modal').on('hide.bs.modal', function (e) {
                if (self.needRefreshList){
                    self.initList();
                }
            })


            _modal.find(".choose-logo").off("click").on("click", function(){
                //点击选择文件
                var pId = _modal.find('div.ndp-drop-wrapper[name="product-drop"]').data("val");
                if ('' == pId || '-1' == pId){
                    _modal.find(".select-product-container").find(".error-remainder").removeClass("hide");
                   return false;
                }
                _modal.find(".select-product-container").find(".error-remainder").addClass("hide");
                self.productId = pId;
                _modal.find('.choose-info').addClass("hide");
                _modal.find('.upload-info').removeClass("hide");
            })

            _modal.find(".return").off("click").on("click", function(){
                //文件上传处点返回
                _modal.find('.choose-info').removeClass("hide");
                _modal.find('.upload-info').addClass("hide");
            })

            _modal.find(".upload").off("click").on("click", function(){
                //文件上传处点击上传
                var fileN = _modal.find('input[name="file"]', ".add-logo-container").val();
                //需要校验文件选了没有
                if (!fileN || "" == fileN){
                    _modal.find(".add-logo-container").find('.error-remainder').removeClass("hide");
                    return false;
                }
                _modal.find(".add-logo-container").find('.error-remainder').addClass("hide");

                //构造上传的请求
                var formData = new FormData();
                formData.append("files", _modal.find('input[name="file"]', ".add-logo-container").get(0).files[0]);
                if (self.templateId){
                    formData.append("templateId", self.templateId);
                }

                formData.append("productId", self.productId);
                _modal.find(".upload-result-c").empty();

                $.ajax({
                    xhrFields: {
                        withCredentials: true
                    },
                    url:  apiUrl + "/ecProductLogo/upload",
                    type: 'POST',
                    dataType: 'json',
                    data: formData,
                    cache: false,
                    processData: false,
                    contentType: false,
                    beforeSend: function(){
                        Kit.loading.show($("#add-logo-dialog"));
                    },
                    success: function(res){
                        if (res.flag == "success"){
                            var zips = res.data;
                            if (zips){
                                var szip = zips[0];
                                if (szip.success){
                                    _modal.modal("hide");
                                    Kit.alert_success("上传成功");
                                    self.initList();
                                } else {
                                    //部分成功 关闭窗口时，也应该重新查询一次列表
                                    self.needRefreshList = true;
                                    if (Kit.isEmptyObject(szip.errors)){

                                    } else {
                                        var upErrors = szip.errors;
                                        if (upErrors["duplication"]){
                                            _modal.find(".upload-result-c").append(' <div class="error-remainder">\
                                                <span class="font-icon font-icon-attention upload-result-icon"></span>' + I18N.getText("templateDetail", "duplicateLogo") +
                                                '</div>');
                                        }

                                        if (upErrors["invalid_name"]){
                                            _modal.find(".upload-result-c").append(' <div class="error-remainder">\
                                                <span class="font-icon font-icon-attention upload-result-icon"></span>' + I18N.getText("templateDetail", "invalidName") +
                                                '</div>');
                                        }

                                        if (upErrors["style_group_too_much"]){
                                            _modal.find(".upload-result-c").append(' <div class="error-remainder">\
                                                <span class="font-icon font-icon-attention upload-result-icon"></span>' + I18N.getText("templateDetail", "linkedMaxStyleGroups") +
                                                '</div>');
                                        }
                                    }
                                }
                            }
                        } else {
                            Kit.alert2(res.errorMsg && res.errorMsg != "" ? res.errorMsg : I18N.getText("templateDetail", "uploadFailed"));
                        }
                    },
                    complete: function(){
                        Kit.loading.hide($("#add-logo-dialog"));
                    },
                    error: function(){
                        Kit.alert2(I18N.getText("templateDetail", "uploadFailed"));
                        _modal.modal("hide");
                    }
                })

            })
        }

        this.initList = function(){
            var param = {
                templateId : self.templateId,
                pSize : 5,
                cPage : 1
            }
            self.param = param;
            self.getLogos(param);
        }

        this.getLogos = function(param){
            Kit.loading.show(self.$root)
            var productGroupsContainer = self.$root.find(".logo-result-container");
            productGroupsContainer.empty();
            http.work('/ecProductLogo/list', param, 'POST').then(function(res) {
                if (res.flag == "success"){
                    var productGroups = res.data.productLogos;
                    if (productGroups){
                        $.each(productGroups, function(i, productGroup){
                            var _productGroupT = _.template($('#element-group-each-t').text())({productName:productGroup.productName,
                                productId:productGroup.productId, templatInfo : {templates : productGroup.templates, 
                                    relateInfo : I18N.getText("templateDetail", "relatedTemplates",
                                    [productGroup.templates ?  productGroup.templates.length : 0])} });
                            productGroupsContainer.append(_productGroupT);

                            //填充logo
                            var _productContainer = productGroupsContainer.find('div[productId="' + productGroup.productId + '"]');
                            _productContainer.data("colorGroups", productGroup.colorGroups);
                            var fContainer = _productContainer.find(".f-container");
                            var sContainer = _productContainer.find(".s-container");
                            var _defaultColorGroup = _.find(productGroup.colorGroups, function(_color){
                                return _color.colorName.toLowerCase() == self.defaultColor;
                            })

                            if (_defaultColorGroup && _defaultColorGroup.styleGroups){
                                $.each(_defaultColorGroup.styleGroups, function(sI, styleGroup){
                                    var _styleGroupId = styleGroup.styleGroupId;
                                    var _logos = styleGroup.logos;
                                    var title = styleGroup.styleGroupId < 10 ? "0" + styleGroup.styleGroupId : styleGroup.styleGroupId;
                                    if (_logos){
                                        var f = _logos["F"];
                                        self.renderLogo(f, fContainer, _styleGroupId, 'F' + title);

                                        //辅
                                        var s = _logos["S"];
                                        self.renderLogo(s, sContainer, _styleGroupId, 'S' + title);
                                    } else {
                                        self.renderLogo(null, fContainer, _styleGroupId, 'F' + title);
                                        self.renderLogo(null, sContainer, _styleGroupId, 'S' + title);
                                    }
                                })
                            }

                            //每个站点至少要5组样式，如果不满足则用占位符填充
                            var fplaceholders = 5 - fContainer.find("li").length;
                            if (fplaceholders > 0){
                                while(fplaceholders > 0 ){
                                    self.renderLogo(null, fContainer, "-1", "");
                                    fplaceholders--;
                                }
                            }

                            var splaceholders = 5 - sContainer.find("li").length;
                            if (splaceholders > 0){
                                while(splaceholders > 0 ){
                                    self.renderLogo(null, sContainer, "-1", "");
                                    splaceholders--;
                                }
                            }
                        })

                        if (!self.templateId){
                            self.$root.find(".relate-template-container").removeClass("hide");
                        }
                    }

                    self.$root.find(".circle").removeClass("active");
                    self.$root.find(".circle-" + self.defaultColor).addClass("active");
                    self.adjuestElementWidth();
                    self.renderPage(param.cPage, param.pSize, res.data.paginator.tSize);
                } else {

                }
                Kit.loading.hide(self.$root)
            }, function(){
                Kit.loading.hide(self.$root)
            })
        }

        this.renderLogo = function(_logo, _logoContainger, _styleGroupId, _title){
            var fP = './imgs/template-logo-default.png';
            var fliC = 'default-i';
            if (_logo != null){
                fP = _logo.elementPreview;
                fliC = "";
            }
            var fE = '<li class="' + fliC + '"  styleGroupId="' + _styleGroupId + '">\
                                            <div class="element-img-div" title="' + (_title) + '">\
                                            <img class="liImg" src="' + fP + '" /></div>\
                                        </li>';
            _logoContainger.append(fE);
        }

        this.renderPage = function(_currentPage, _perPage, _totalSize) {
            var pagerE = $("div.ndp-page-wrapper[name=drop-page]", self.$root);
            pagerE.empty();
            if (!_totalSize || _totalSize == 0){
                return;
            }
            pagerE.page({
                type: 3, //1 普通，2 带显示条数，3，简洁紧凑格式的菜单
                totalItems: _totalSize, //总共有n条数据
                perPage: _perPage, //每页默认显示10条
                currentPage: _currentPage,
                perPages: [5, 10, 20, 50]
            }).off("PAGE_CHANGE").on("PAGE_CHANGE", function(e) { //页数点击 事件
                console.log(e.originalEvent.data); //{currentPage: 第几页 int} currentPage: 1
                self.param.cPage = e.originalEvent.data.currentPage;
                self.getLogos(self.param);
            }).off("SHOW_ITEMS_CHANGE").on("SHOW_ITEMS_CHANGE", function(e) { //页数点击 事件
                console.log(e.originalEvent.data); //{currentPage: 第几页 int}  {currentPage: 1, perpage: 50}
                self.param.cPage = e.originalEvent.data.currentPage;
                self.param.pSize = e.originalEvent.data.perpage;
                self.getLogos(self.param);
            });
        }

        this.event = function() {
            //modal打开先请求元素数据
            self.$root.find('#search-area .upload-logo').off('click').on('click', $.proxy(self.openAddLogoDialog, self));
            //自适应
            $(window).resize(function() {
                self.adjuestElementWidth();
            });


            //切换颜色 按颜色过滤
            self.$root.off('click', '.circle').on('click', '.circle',  $.proxy(self.filterByColor, self));

            //关联模板处 展开折叠
            self.$root.off('click', '.collapse-sign').on('click', '.collapse-sign', function(e){
                $(this).toggleClass("fold").toggleClass("unfold");
                $(this).parents(".relate-template-container").find(".relate-templates").toggleClass("hide");
            })
        }

        this.filterByColor = function(e){
            var _cE = $(e.target);
            $(_cE).parents(".element-color-select").find(".circle").removeClass("active");
            $(_cE).addClass("active");
            var _pGroupContainer = $(_cE).parents(".element-group-each");
            var color = $(_cE).attr("data-color");
            var _logoContainer;
            var title;
            if ($(_cE).parents(".f-color-container").length){
                _logoContainer = _pGroupContainer.find(".f-container");
                title = "F";
            } else {
                _logoContainer = _pGroupContainer.find(".s-container");
                title = "S";
            }
            _logoContainer.empty();

            var colorGroups = _pGroupContainer.data("colorGroups");
            //获取当前颜色对应的样式组
            var _defaultColorGroup = _.find(colorGroups, function(_color){
                return _color.colorName.toLowerCase() == color;
            })

            if (_defaultColorGroup && _defaultColorGroup.styleGroups){
                $.each(_defaultColorGroup.styleGroups, function(sI, styleGroup){
                    var _styleGroupId = styleGroup.styleGroupId;
                    var _logos = styleGroup.logos;
                    var cTitle = title + (_styleGroupId.length == 1 ? "0" + _styleGroupId : _styleGroupId);
                    if (_logos){
                        var f = _logos[title];
                        self.renderLogo(f, _logoContainer, _styleGroupId,cTitle);
                    } else {
                        self.renderLogo(null, _logoContainer, _styleGroupId, cTitle);
                    }
                })
            }

            //每个站点每个颜色
            // 至少要5组样式，如果不满足则用占位符填充
            var splaceholders = 5 - _logoContainer.find("li").length;
            if (splaceholders > 0){
                while(splaceholders > 0 ){
                    self.renderLogo(null, _logoContainer, "-1", "");
                    splaceholders--;
                }
            }

            self.adjuestElementWidth();

            // var param = {
            //     productId : _productId,
            //     color : color,
            //     major : major,
            //     templateId : self.templateId
            // }
            // http.work('/ecProductLogo/filter', param, 'POST').then(function(res) {
            //     if (res.flag == "success"){
            //         var _logoContainer;
            //         var _anotherContainer;
            //         var title;
            //         if (major){
            //             _logoContainer = _pGroupContainer.find(".f-container");
            //             _anotherContainer = _pGroupContainer.find(".s-container");
            //             title = "F";
            //         } else {
            //             _logoContainer = _pGroupContainer.find(".s-container");
            //             _anotherContainer = _pGroupContainer.find(".f-container");
            //             title = "S";
            //         }
            //         _logoContainer.empty();
            //
            //         //以切换颜色的另一块为基准，保证主辅的样式组是相互对应的
            //         var _anotherLogos = _anotherContainer.find("li");
            //         $.each(_anotherLogos, function(i, _anotherLogo){
            //             var _styleGroupId = $(_anotherLogo).attr("styleGroupId");
            //             if (_styleGroupId != -1){
            //                 var cTitle = title + (_styleGroupId.length == 1 ? "0" + _styleGroupId : _styleGroupId);
            //                 var _logo = res.data[_styleGroupId];
            //                 self.renderLogo(_logo, _logoContainer, _styleGroupId, cTitle);
            //                 if (_logo){
            //                     delete res.data[_styleGroupId];
            //                 }
            //             }
            //         });
            //
            //         //继续遍历新增的样式组对应的logo
            //         $.each(res.data, function(i, _logo){
            //             var _styleGroupId = _logo.elementStyleGroupId;
            //             var cTitle = title + (_styleGroupId < 10 ? "0" + _styleGroupId : _styleGroupId);
            //             self.renderLogo(_logo, _logoContainer, _styleGroupId, cTitle);
            //         })
            //         //每个站点每个颜色
            //         // 至少要5组样式，如果不满足则用占位符填充
            //         var splaceholders = 5 - _logoContainer.find("li").length;
            //         if (splaceholders > 0){
            //             while(splaceholders > 0 ){
            //                 self.renderLogo(null, _logoContainer, "-1", "");
            //                 splaceholders--;
            //             }
            //         }
            //
            //         self.adjuestElementWidth();
            //     } else {
            //         //todo
            //     }
            //
            // }, function(){
            //
            // });
        }

        /**
         * 添加元素dialog
         */
        this.openAddLogoDialog = function() {
            //请求站点数据，渲染下拉列表，打开modal
            http.work('/productmanage/findAllByOrgId', null, 'POST').then(function(res) {
                if (res.succeed) {
                    var products = [];
                    _.each(res.data, function(el) {
                        products.push({id: el.prodId, text: el.prodName});
                    });
                    self.$root.find("div.ndp-drop-wrapper[name=product-drop]").empty().drop({
                        data: products,
                        name: "productDrop",
                        placeholder : I18N.getText('templateDetail', 'pleaseSelectWebsite'),
                        caret:"glyphicon-menu-right"
                    }).off("ITEM_CLICK").on("ITEM_CLICK", function(e) { //下拉选择项点击事件
                    }).val({"val" : -1 , "text" : I18N.getText('templateDetail', 'pleaseSelectWebsite')});
                    self.$root.find("#add-logo-dialog").modal('show');
                } else {
                    Kit.alert2(res.errorMsg);
                }
            });
        }

        /**
         * 调整元素图片的位置
         */
        this.adjuestElementWidth = function() {
            if (self.$root.hasClass("hidden")){
                return;
            }

            self.$root.find('.element-img-container').each(function() {
                var width = $(this).width() - 1; //外面容器的宽度.
                var w = 82 * 5; //每个元素80px
                var marginRight = (width - w) / 4; //margin-right的值,最后一个为0;
                if (marginRight < 15){
                    marginRight = 15;
                    var _half = w + marginRight * 4;
                    var tW = $(this).parents(".element-group-each").width();
                    var _margin = tW - 2 * _half;
                    $(this).parents(".element-group-each").find(".style-group-container").css('width',  _half + 'px');
                    $(this).parents(".element-group-each").find(".f-style-group-container").css('margin-right',  _margin + 'px');
                }

                var lis = $(this).find('ul li');
                lis.css('margin-right', marginRight + 'px');
                $.each(lis, function(i, _li){
                    //每5个一行
                    if ( (i + 1)  % 5 == 0){
                        $(_li).css('margin-right', '0px');
                    }
                });

            })

        }
    }
    return new me();
});